package deyi.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import deyi.cache.AppCache;
import deyi.log.AppLogger;
import deyi.nbtype.DeviceConfigInfo;
import deyi.nbtype.DeviceDownlinkConfig;
import deyi.nbtype.DeviceIpMap;
import deyi.udp.UdpServer;
import deyi.utils.CommonUtil;
import deyi.utils.NBHandler;
import deyi.utils.SpringContextUtil;
import org.apache.commons.io.IOUtils;
import org.apache.mina.core.buffer.IoBuffer;

import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.ConcurrentHashMap;

public class HttpEventHandle implements HttpHandler {

    public void handle(HttpExchange httpExchange) throws IOException {
        String requestMethod = httpExchange.getRequestMethod();
        if(requestMethod.equalsIgnoreCase("POST")){
            AppCache appCache = (AppCache)SpringContextUtil.getBean("appcache");
            String content = IOUtils.toString(httpExchange.getRequestBody());
            AppLogger.logInfo("middle received device cache from server..." + "[config content]: " + content);
            JSONArray jsonArray = JSONArray.parseArray(content);
            for (Object jsObj:jsonArray) {
                DeviceConfigInfo deviceConfigInfo =  JSONObject.parseObject(jsObj.toString(),DeviceConfigInfo.class);
                ConcurrentHashMap<Integer,byte[]> mapConfig = appCache.getDeviceConfigMap().get(deviceConfigInfo.getDeviceSn());
                if(mapConfig == null){
                    mapConfig = new ConcurrentHashMap<Integer, byte[]>();
                    mapConfig.put(deviceConfigInfo.getConfigId(),NBHandler.getProduceConfigData(deviceConfigInfo));
                    appCache.getDeviceConfigMap().put(deviceConfigInfo.getDeviceSn(),mapConfig);
                }else{
                    mapConfig.put(deviceConfigInfo.getConfigId(),NBHandler.getProduceConfigData(deviceConfigInfo));
                }
            }

            JSONObject jsobj = new JSONObject();
            jsobj.put("msg","received data.");
            String responseMsg = jsobj.toString();
            httpExchange.getResponseHeaders().add("Content-Type","application/json");
            httpExchange.getResponseHeaders().add("charset","UTF-8");
            httpExchange.sendResponseHeaders(200, responseMsg.length());
            OutputStream outputStream = httpExchange.getResponseBody();
            outputStream.write(responseMsg.getBytes());
            outputStream.flush();
            outputStream.close();
        }
    }
}
